var router = require('koa-router')();
const tasks = require('../models/tasks')
const { verifyToken } = require('../authUtil');

router.prefix('/api/tasks');

// Token验证中间件
const authenticate = function *(next) {
  const token = this.headers.authorization;
  if (!token) {
    this.body = { status: 1, msg: 'No token provided' };
    return;
  }

  try {
    const decoded = verifyToken(token.replace('Bearer ', ''));
    if (!decoded) {
      this.body = { status: 1, msg: 'Invalid token' };
      return;
    }
    console.log(decoded)
    this.state.user = decoded
    yield next
  } catch (error) {
    console.log(error)
    this.body = { status: 1, msg: 'Token is not valid' };
  }
};

router.post('/', authenticate, function *(next) {
  const {text} = this.request.body
  const userIdFromToken = this.state.user.userId
  const result = tasks.addTask(text, userIdFromToken)
  this.body = result
});

router.delete('/:id', authenticate, function *(next) {
  const {id} = this.params
  const userIdFromToken = this.state.user.userId
  const result = tasks.removeById(id, userIdFromToken)
  this.body = result
});

router.delete('/', authenticate, function *(next) {
  const userIdFromToken = this.state.user.userId
  const result = tasks.removeByuserId(userIdFromToken)
  this.body = result
});

router.put('/:id', authenticate, function *(next) {
  const {text} = this.request.body
  const {id} = this.params
  const userIdFromToken = this.state.user.userId
  const result = tasks.updateById(id, text, userIdFromToken);
  this.body = result;
});

router.get('/', authenticate, function *(next) {
  const userIdFromToken = this.state.user.userId
  console.log(userIdFromToken)
  const rows = tasks.getAll(userIdFromToken)
  this.body = rows
});

module.exports = router;
